import 'package:flutter/material.dart';
import 'package:lark_flutter_learn/widget/function/shop_cart.dart';

import 'InheritedProvider.dart';

class ShopCardPage extends StatelessWidget {
  const ShopCardPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("购物车"),
      ),
      body: const ProviderRoute(),
    );
  }
}

class ProviderRoute extends StatefulWidget {
  const ProviderRoute({super.key});

  @override
  _ProviderRouteState createState() => _ProviderRouteState();
}

class _ProviderRouteState extends State<ProviderRoute> {

  @override
  void didUpdateWidget(ProviderRoute oldWidget) {
    // TODO: implement didUpdateWidget
    super.didUpdateWidget(oldWidget);
    print("xxx");
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: ChangeNotifierProvider<CartModel>(
        data: CartModel(),
        child: Builder(builder: (context) {
          return Column(
            children: <Widget>[
              Consumer<CartModel>(
                builder: (context, cart) => Text("总价: ${cart?.totalPrice}"),
              ),
              Builder(builder: (context) {
                print("ElevatedButton build"); //在后面优化部分会用到
                return ElevatedButton(
                  child: const Text("添加商品"),
                  onPressed: () {
                    //给购物车中添加商品，添加后总价会更新
                    var cart = ChangeNotifierProvider.of<CartModel>(
                      context,
                      listen: false,
                    );
                    cart!.add(Item('ss', 20.0, 1));
                  },
                );
              }),
            ],
          );
        }),
      ),
    );
  }
}
